<template>
  <el-card style="height: 100%">
    <!-- 1.面包屑 -->
    <MyBread url="administrator" level1="系统管理" level2="账户管理" />
    <!-- 2.搜索 -->
    <el-input
      placeholder="请输入用户名"
      v-model="search"
      class="with-input"
      clearable
    >
      <el-button
        slot="append"
        icon="el-icon-search"
        @click="searchAccount()"
      ></el-button>
    </el-input>
    <!-- 3.表格 -->
    <UserTable
      :userData="UserData"
      :handleDelete="handleDelete"
      :handleEdit="handleEdit"
      :handleRole="handleRole"
    />
    <!-- 4.分页 -->
    <el-pagination
      style="margin-top: 30px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[2, 4, 6, 8]"
      :page-size="limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="length"
    >
    </el-pagination>
    <!-- 编辑用户的对话框 -->
    <el-dialog
      title="编辑账户信息"
      :visible.sync="dialogFormVisible"
      width="440"
    >
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item>
          <el-input
            v-model="form.username"
            readonly
            prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            placeholder="密码"
            prefix-icon="el-icon-lock"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <span class="el-input__inner icon">{{
            handleRole(form.rolename)
          }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelModifyButton()">取 消</el-button>
        <el-button type="primary" @click="updateAccountButton()"
          >修改密码</el-button
        >
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import UserTable from "./UserTable.vue";
export default {
  name: "User",
  components: { UserTable },
  data() {
    return {
      search: "", // 搜索输入框输入的内容
      page: 1, // 当前页数
      limit: 2, // 每条页面条数
      length: 0, // 获取数据的长度
      dialogFormVisible: false, // 控制用户对话框的显示与隐藏
      UserData: [], // 请求获取的用户数据
      // 用户表单
      form: {
        username: "",
        password: "",
        rolename: "",
        createTime: "",
      },
      // 用户表单验证规则
      rules: {
        // 用户名、登录角色完全只读 ==> 不能修改，不用添加验证规则
        password: [
          { validator: this.validatePass, trigger: ["blur", "change"] },
        ],
      },
    };
  },
  methods: {
    // 对于角色显示的处理
    handleRole(rolename) {
      if (rolename === "student") {
        return "学员";
      } else if (rolename === "coach") {
        return "教练";
      } else {
        return "管理员";
      }
    },
    // 取消更新或添加操作 -- 重新获取数据
    cancelModifyButton() {
      this.dialogFormVisible = false;
      this.getUserList();
      this.getUserListLength();
    },
    // 获取账户列表长度
    getUserListLength() {
      this.$https.getUser({ like: this.search }).then((res) => {
        this.length = res.data.length;
      });
    },
    // 搜索功能实现
    searchAccount() {
      this.getUserListLength();
      this.limit = 2;
      this.page = 1;
      this.getUserList();
      this.search = "";
    },
    // 获取账户数据
    async getUserList() {
      const { data } = await this.$https.getUser({
        page: this.page,
        limit: this.limit,
        like: this.search,
      });
      this.UserData = data;
    },
    // 当每页条数发生变化使调用
    handleSizeChange(val) {
      this.limit = val;
      this.page = 1;
      this.getUserList();
    },
    // 当页数发生变化时调用
    handleCurrentChange(val) {
      this.page = val;
      this.getUserList();
    },
    // 根据id更新用户信息到json-server数据库
    updateAccountButton() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          this.dialogFormVisible = false;
          // 发送数据
          await this.$https.updateUserData("/login", this.form.id, this.form);
          // 重新获取用户数据
          this.page = 1;
          this.search = "";
          this.getUserList();
          this.getUserListLength();
          // 清空表单
          this.form = {};
          // 提示信息
          this.$message.success("修改用户成功");
        } else {
          this.$message.warning("表单验证信息不通过");
        }
      });
    },
    // 删除账户 -- 删除账户对应的学员或教练信息
    async handleDelete(_, row) {
      // 验证是否拥有修改权限
      if (!(await this.haveThisPermission(this.$route.path, "删除账户"))) {
        this.$message.warning("您当前没有该权限");
        return;
      }
      // 判断删除的账户是否为管理员
      if (row.rolename === "administrator") {
        this.$message.error("管理员不能删除");
        return;
      } else {
        // 删除账户操作
        await this.$https.deleteUserData("/login", row.id);
        // 删除账户成功后，删除对应用户信息
        // 1. 获取账户对应的用户 -- 学员/教练
        const { data } = await this.$https.getUserData({
          url: "/" + row.rolename,
          identify: row.username,
        });
        // 2. 获取信息成功后根据id删除该用户
        await this.$https.deleteUserData("/" + row.rolename, data[0].id);
        // 重新获取用户数据
        this.page = 1;
        this.search = "";
        this.getUserList();
        this.getUserListLength();
        // 提示信息
        this.$message.success("用户删除成功");
      }
    },
    // 编辑用户信息
    async handleEdit(_, row) {
      // 验证是否拥有修改权限
      if (!(await this.haveThisPermission(this.$route.path, "修改账户"))) {
        this.$message.warning("您当前没有该权限");
        return;
      }
      // 回显数据，显示对话框
      this.form = row;
      this.dialogFormVisible = true;
    },
  },
  async mounted() {
    // 获取用户信息总长度
    this.getUserListLength();
    // 获取用户数据
    this.getUserList();
  },
};
</script>

<style scoped>
.with-input {
  width: 500px;
  margin-top: 30px;
  margin-bottom: 30px;
  margin-right: 10px;
}
</style>